package ajax;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.NewsModel;
import models.UserModel;
import data.NewsData;
import data.UserData;

public class AjaxListNewsServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String page = (String) request.getParameter("page");
		
		if(page == null) {
			page = "999";
		}
		
		NewsData newsData = new NewsData();
		newsData.setPage(Integer.parseInt(page));
		ArrayList<NewsModel> list_news = newsData.list();
		
		List<String> ids = new ArrayList<String>();
		for (int i = 0; i < list_news.size(); i++) {
			if (!ids.contains(list_news.get(i).getCreator())) {
				ids.add(list_news.get(i).getCreator());
			}
		}
		
		UserData userData = new UserData();
		Map<String, UserModel> users = userData.getByManyId(ids);
		
		request.setAttribute("list_news", list_news);
		request.setAttribute("users", users);
		try {
			request.getRequestDispatcher("/ajax/list_news.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
